<?php
require $root.'/StackStruct/StackStruct.php';

/**
 * 匹配花括号
 * Class MatchBracket
 */
class MatchBracket
{
    /**
     * 判断花括号是否有效封闭
     * @param string $str
     * @return bool
     */
    public function isValid(string $str): bool
    {
        $stackStruct = new StackStruct();
        //若字符串长度为奇数，则肯定不封闭
        if (strlen($str) % 2 == 1) {
            return false;
        }

        //先将花括号字符串依次入栈,若遇到 ] ) },需查看栈顶是否对应是 [ ( {
        for ($i = 0; $i < strlen($str); $i++) {
            if (!$stackStruct->isEmpty() && $str[$i] == "]" && $stackStruct->peek() != "[") {
                return false;
            } elseif (!$stackStruct->isEmpty() && $str[$i] == ")" && $stackStruct->peek() != "(") {
                return false;
            } elseif (!$stackStruct->isEmpty() && $str[$i] == "}" && $stackStruct->peek() != "{") {
                return false;
            } elseif (!$stackStruct->isEmpty() && $str[$i] == "]" && $stackStruct->peek() == "[") {
                $stackStruct->pop(); //出栈抵消
            } elseif (!$stackStruct->isEmpty() && $str[$i] == ")" && $stackStruct->peek() == "(") {
                $stackStruct->pop(); //出栈抵消
            } elseif (!$stackStruct->isEmpty() && $str[$i] == "}" && $stackStruct->peek() == "{") {
                $stackStruct->pop(); //出栈抵消
            } else {
                $stackStruct->push($str[$i]);
            }
        }
        //如 "$str=[({" ,最后栈不为空，则表示括号不封闭
        if (!$stackStruct->isEmpty()) {
            return false;
        }
        return true;
    }
}